"""Java相关的衍生配置处理"""

from typing import Dict, Any, Set
from ...type.types import MySQLTypeInfo
from ...type.converters import get_java_type
from src.core.common.naming import to_pascal_case
from src.base import bera

def derive_java_config(meta_info: Dict[str, Any]) -> Dict[str, Any]:
    """处理meta.json的Java相关衍生配置

    处理字段级衍生配置:
    - columns.*.derived.java.type: Java类型
    - columns.*.derived.java.import: 导入语句
    - columns.*.derived.java.default_value: 默认值
    - columns.*.derived.java.getter: getter方法名
    - columns.*.derived.java.setter: setter方法名

    处理表级衍生配置:
    - table.derived.java.imports: 所有需要的导入语句集合
      (由字段级的java.import去重排序后生成)
    - table.derived.java.package_path: 包名对应的文件系统路径
      (由table.sql.package转换而来,例如com.miaoma.auto -> com/miaoma/auto)
    - table.derived.java.primary_key_java_type: 主键的Java类型
      (由主键列的java.type获得)

    :param meta_info: meta.json格式的结构体
    :return: 更新后的结构体,可以继续传递给其他derived函数处理
    """
    bera.logger.debug("====== 开始处理Java相关衍生配置 ======")

    # 确保table和derived.java存在
    if "table" not in meta_info:
        meta_info["table"] = {}
    if "derived" not in meta_info["table"]:
        meta_info["table"]["derived"] = {}
    if "java" not in meta_info["table"]["derived"]:
        meta_info["table"]["derived"]["java"] = {}

    # 处理package_path
    if "mark" in meta_info["table"] and "package" in meta_info["table"]["mark"]:
        package = meta_info["table"]["mark"]["package"]
        package_path = package.replace(".", "/")
        meta_info["table"]["derived"]["java"]["package_path"] = package_path

    # 用于收集所有import语句
    imports: Set[str] = set()

    bera.logger.debug("开始遍历处理列...")
    # 遍历处理每个column
    for column_name, column_info in meta_info["columns"].items():
        bera.logger.debug(f"\n处理列: {column_name}")
        bera.logger.debug(f"列的SQL配置: {column_info.get('sql', {})}")

        # 从column_info中提取类型信息
        sql_type = column_info["sql"]["type"]
        type_info = MySQLTypeInfo(
            name=sql_type["name"].upper(),
            length=sql_type.get("length"),
            precision=sql_type.get("precision"),
            scale=sql_type.get("scale")
        )

        if column_info["sql"].get("primary_key", False):
            bera.logger.debug(f"发现主键列: {column_name}")
            bera.logger.debug(f"主键列SQL类型信息: {type_info}")

        try:
            # 使用get_java_type()获取Java类型
            java_type = get_java_type(type_info)
            bera.logger.debug(f"转换后的Java类型: {java_type}")

            # 添加derived配置
            if "derived" not in column_info:
                column_info["derived"] = {}
            if "java" not in column_info["derived"]:
                column_info["derived"]["java"] = {}

            # 设置Java类型
            column_info["derived"]["java"]["type"] = java_type

            # 设置getter和setter方法名
            pascal_name = to_pascal_case(column_name)
            column_info["derived"]["java"]["getter"] = f"get{pascal_name}"
            column_info["derived"]["java"]["setter"] = f"set{pascal_name}"

            # 设置import语句
            import_stmt = ""
            if java_type in ["LocalDate", "LocalDateTime"]:
                import_stmt = f"java.time.{java_type}"
            elif java_type == "BigDecimal":
                import_stmt = "java.math.BigDecimal"
            column_info["derived"]["java"]["import"] = import_stmt

            # 如果有import语句，添加到集合中
            if import_stmt:
                imports.add(import_stmt)

            # 设置默认值
            nullable = column_info["sql"].get("nullable", True)
            if nullable:
                default_value = "null"
            else:
                default_value = {
                    "Long": "0L",
                    "Integer": "0",
                    "String": "\"\"",
                    "BigDecimal": "BigDecimal.ZERO",
                    "LocalDate": "LocalDate.now()",
                    "LocalDateTime": "LocalDateTime.now()",
                    "Boolean": "false"
                }.get(java_type, "null")
            column_info["derived"]["java"]["default_value"] = default_value

            # 如果是主键列,设置table.derived.java.primary_key_java_type
            if column_info["sql"].get("primary_key", False):
                meta_info["table"]["derived"]["java"]["primary_key_java_type"] = java_type
                bera.logger.debug(f"设置主键Java类型为: {java_type}")

        except Exception as e:
            bera.logger.debug(f"类型转换异常: {str(e)}")
            # 如果转换失败,使用默认映射
            type_map = {
                "BIGINT": ("Long", "", "0L"),
                "INT": ("Integer", "", "0"),
                "INTEGER": ("Integer", "", "0"),
                "TINYINT": ("Integer", "", "0"),
                "VARCHAR": ("String", "", "\"\""),
                "CHAR": ("String", "", "\"\""),
                "TEXT": ("String", "", "\"\""),
                "DECIMAL": ("BigDecimal", "java.math.BigDecimal", "BigDecimal.ZERO"),
                "DATE": ("LocalDate", "java.time.LocalDate", "LocalDate.now()"),
                "DATETIME": ("LocalDateTime", "java.time.LocalDateTime", "LocalDateTime.now()"),
                "TIMESTAMP": ("LocalDateTime", "java.time.LocalDateTime", "LocalDateTime.now()")
            }
            if "derived" not in column_info:
                column_info["derived"] = {}
            if "java" not in column_info["derived"]:
                column_info["derived"]["java"] = {}

            java_type, import_stmt, default_value = type_map.get(type_info.name, ("String", "", "\"\""))
            column_info["derived"]["java"]["type"] = java_type
            column_info["derived"]["java"]["import"] = import_stmt
            column_info["derived"]["java"]["default_value"] = default_value if not column_info["sql"].get("nullable", True) else "null"

            # 设置getter和setter方法名
            pascal_name = to_pascal_case(column_name)
            column_info["derived"]["java"]["getter"] = f"get{pascal_name}"
            column_info["derived"]["java"]["setter"] = f"set{pascal_name}"

            # 如果有import语句，添加到集合中
            if import_stmt:
                imports.add(import_stmt)

            # 如果是主键列,设置table.derived.java.primary_key_java_type
            if column_info["sql"].get("primary_key", False):
                meta_info["table"]["derived"]["java"]["primary_key_java_type"] = java_type
                bera.logger.debug(f"设置主键Java类型为(异常处理): {java_type}")

    # 设置表级的imports
    meta_info["table"]["derived"]["java"]["imports"] = sorted(list(imports))

    # 如果没有找到主键,默认使用Long类型
    if "primary_key_java_type" not in meta_info["table"]["derived"]["java"]:
        bera.logger.debug("未找到主键列，使用默认类型: Long")
        meta_info["table"]["derived"]["java"]["primary_key_java_type"] = "Long"

    bera.logger.debug(f"最终的主键Java类型: {meta_info['table']['derived']['java']['primary_key_java_type']}")
    bera.logger.debug("====== Java相关衍生配置处理完成 ======")
    return meta_info